package com.example.demo.config;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * 自定义验证方式
 *
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;

    /**
     * 构造一个自定义验证器下的验证方式
     *
     * @param retryLimitCredentialsMatcher 自定义验证器
     */
    public MyShiroRealm(CredentialsMatcher retryLimitCredentialsMatcher) {
        super(retryLimitCredentialsMatcher);
    }

    //角色权限和对应权限添加
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {//获取登录用户名
        return new SimpleAuthorizationInfo();
    }

    //用户认证，在登录失败时抛出对应的异常
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //在Post请求的时候会先进认证，然后再到请求
        if (authenticationToken.getPrincipal() == null) {
            return null;
        }
        //获取用户信息
        String username = authenticationToken.getPrincipal().toString();
        User user = userMapper.selectByUsername(username);
        if (user == null)//账号不存在，抛异常
            throw new UnknownAccountException();
        else {
            //这里验证authenticationToken和simpleAuthenticationInfo的信息
            return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        }
    }
}
